package com.adaydayup.week1;

/**
 * 396. 旋转函数
 * 输入: nums = [4,3,2,6]
 * 输出: 26
 * 解释:
 * F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
 * F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
 * F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
 * F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
 * 所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
 */
public class MaxRotateFunction {
    public int maxRotateFunction(int[] nums) {
        int len=nums.length;
        int[] sum=new int[2*len+10];
        for (int i = 1; i <= 2*len; i++) {
            sum[i]=sum[i-1]+nums[(i-1)%len];
        }
        int ans=0;
        for (int i = 1; i <=len ; i++) {
            ans+=nums[i-1]*(i-1);
        }
        for (int i = len+1,cur=ans; i <=2*len ; i++) {
            cur+=nums[(i-1)%len]*(len-1);
            cur-=sum[i-1]-sum[i-len];
            if (cur>ans){
                ans=cur;
            }
        }
        return ans;
    }

}
